<template>
  <div v-show="!isMain && !isView" class="add-equip-detail">
    <px-scrollbar class="add-equip-content">
      <px-button style="margin: 16px 0 -4px" type="primary" icon="ArrowLeft" @click="backMainPage">返回</px-button>
      <px-form ref="formRef" :inline="true" :model="formValue" :rules="rules" label-position="right" label-width="136px">
        <EditDropDown dropdownTitle="指标信息">
          <template v-slot:content>
            <px-row>
              <px-col :span="8">
                <px-form-item label="指标名称" prop="measureName">
                  <px-input v-model="formValue.measureName" placeholder="请输入" maxlength="50" clearable />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="指标单位" prop="measureUnit">
                  <px-select v-model="formValue.measureUnit" filterable clearable placeholder="请选择" style="width: 100%">
                    <px-option v-for="item in measureUnitList" :key="item.id" :label="item.name" :value="item.value" />
                  </px-select>
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="保留位数" prop="decimalPlaces">
                  <px-input-number v-model="formValue.decimalPlaces" :min="1" controls-position="right" />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="指标类型" prop="measureTypeCode">
                  <px-select v-model="formValue.measureTypeCode" filterable clearable placeholder="请选择" style="width: 100%">
                    <px-option v-for="item in measureTypeCodeList" :key="item.id" :label="item.name" :value="item.value" />
                  </px-select>
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="生成衍生指标" prop="isDerived">
                  <px-select v-model="formValue.isDerived" placeholder="请选择" clearable filterable>
                    <px-option v-for="item in isGenerateList" :key="item.value" :label="item.label" :value="item.value" />
                  </px-select>
                </px-form-item>
              </px-col>
              <!-- <px-col
                v-if="
                  formValue.measureTypeCode === '1' ||
                  formValue.measureTypeCode === '2' ||
                  formValue.measureTypeCode === '3' ||
                  formValue.measureTypeCode === '4'
                "
                :span="8"
              >
                <px-form-item label="衍生指标" prop="derivedTypes">
                  <px-select v-model="formValue.derivedTypes" multiple clearable filterable placeholder="请选择" style="width: 100%">
                    <px-option v-for="item in derivedTypesList" :key="item.id" :label="item.name" :value="item.value" />
                  </px-select>
                </px-form-item>
              </px-col>
              <px-col
                v-if="
                  formValue.measureTypeCode === '1' ||
                  formValue.measureTypeCode === '2' ||
                  formValue.measureTypeCode === '3' ||
                  formValue.measureTypeCode === '4'
                "
                :span="8"
              >
                <px-form-item label="衍生指标统计周期" prop="statisticsCycles">
                  <px-select v-model="formValue.statisticsCycles" filterable multiple clearable placeholder="请选择" style="width: 100%">
                    <px-option v-for="item in statisticsCyclesList" :key="item.id" :label="item.name" :value="item.value" />
                  </px-select>
                </px-form-item>
              </px-col> -->
              <!-- <px-col :span="8">
                <px-form-item label="所属厂区" prop="facCode">
                  <px-select v-model="formValue.facCode" placeholder="请选择" clearable filterable @change="formValue.monitorEntityId = ''">
                    <px-option v-for="item in facList" :key="item.id" :label="item.name" :value="item.value" />
                  </px-select>
                </px-form-item>
              </px-col> -->
              <px-col :span="8">
                <px-form-item label="监控实体类型" prop="monitorEntityType">
                  <px-select v-model="formValue.monitorEntityType" placeholder="请选择" clearable filterable @change="changeMonitorEntityType">
                    <px-option v-for="item in monitorEntityTypeList" :key="item.id" :label="item.name" :value="item.value" />
                  </px-select>
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item v-if="formValue.monitorEntityType === 'EQP'" label="监控实体" prop="monitorEntityId">
                  <px-select
                    v-model="formValue.monitorEntityId"
                    clearable
                    filterable
                    remote
                    :remote-method="monitorEntityIdRemote"
                    placeholder="请输入设备编号精确查找"
                    style="width: 100%"
                  >
                    <px-option v-for="item in monitorEntityIdList" :key="item.id" :label="item.name" :value="item.value" />
                  </px-select>
                </px-form-item>
                <px-form-item v-else label="监控实体" prop="monitorEntityId">
                  <px-cascader
                    v-if="formValue.monitorEntityType === 'SYSTEM'"
                    ref="cascaderRef"
                    v-model="formValue.monitorEntityId"
                    style="width: 100%"
                    :props="entityTypeProps"
                    :options="monitorEntityIdList"
                    placeholder="请选择监控实体"
                    clearable
                    filterable
                    @change="cascaderRef.togglePopperVisible()"
                    @focus="focusMonitorEntityIdList"
                  />
                  <px-tree-select
                    v-else
                    v-model="formValue.monitorEntityId"
                    clearable
                    filterable
                    :props="{
                      children: 'children',
                      label: 'name',
                      value: 'code',
                      'check-strictly': 'true'
                    }"
                    :data="monitorEntityIdList"
                    placeholder="请选择"
                    style="width: 100%"
                    @focus="focusMonitorEntityIdList"
                  />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="监控物料" prop="monitorMaterialId">
                  <px-cascader
                    v-model="formValue.monitorMaterialId"
                    filterable
                    clearable
                    style="width: 100%"
                    :options="formValue.measureTypeCode === '4' ? monitorWasteMaterialIdList : monitorMaterialIdList"
                    :props="cascaderProps"
                    placeholder="请选择"
                  />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="指标来源" prop="measureSource">
                  <px-select v-model="formValue.measureSource" placeholder="请选择" clearable filterable>
                    <px-option v-for="item in measureSourceList" :key="item.id" :label="item.name" :value="item.value" />
                  </px-select>
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="标签" prop="measureTags">
                  <px-cascader
                    v-model="formValue.measureTags"
                    filterable
                    clearable
                    style="width: 100%"
                    :options="measureTagList"
                    :props="defaultProps"
                    placeholder="请选择标签"
                  />
                </px-form-item>
              </px-col>
              <px-col :span="24">
                <px-divider />
              </px-col>
              <px-col :span="8">
                <px-form-item label="是否需要计算" prop="isNeedCalculate">
                  <px-radio-group v-model="formValue.isNeedCalculate" :disabled="drawerType === 'edit'" @change="handleChangeIsCalc">
                    <px-radio :label="0">否</px-radio>
                    <px-radio :label="1">是</px-radio>
                    <!-- <px-radio :label="2">指标计算</px-radio> -->
                  </px-radio-group>
                </px-form-item>
              </px-col>
              <px-col v-if="formValue.isNeedCalculate === 0" :span="8">
                <px-form-item label="绑定点位" prop="tagCode">
                  <px-select
                    v-model="formValue.tagCode"
                    :disabled="drawerType === 'edit'"
                    clearable
                    filterable
                    remote
                    :remote-method="tagCodeRemote"
                    placeholder="请输入点位精确查找"
                    style="width: 100%"
                    @change="changeTagCode"
                  >
                    <px-option v-for="item in tagCodeList" :key="item.id" :label="item.name" :value="item.value" />
                  </px-select>
                </px-form-item>
              </px-col>
              <px-col v-if="formValue.isNeedCalculate === 0" :span="8">
                <px-form-item label="点位单位" prop="tagUnitDesc">
                  <px-input v-model="formValue.tagUnitDesc" disabled placeholder="自动带出" maxlength="50" />
                  <div v-if="formValue.measureUnit && formValue.tagCode && formValue.measureUnit !== formValue.tagUnit">
                    <px-icon color="#faad14" style="margin-top: 9px">
                      <Warning />
                    </px-icon>
                    <span style="font-size: 12px; color: #929292">与指标单位不同，可通过计算公式完成单位转换</span>
                  </div>
                </px-form-item>
              </px-col>
            </px-row>
            <px-row style="width: 100%">
              <!-- todo 是否需要计算-是原逻辑 -->
              <px-col v-if="formValue.isNeedCalculate !== 0" :span="12">
                <px-form-item label="计算公式" prop="calculateFormula">
                  <px-input id="myInput" v-model="formValue.calculateFormula" placeholder="自动带出" maxlength="200" type="text" />
                </px-form-item>
              </px-col>
              <px-col v-if="formValue.isNeedCalculate !== 0" :span="12">
                <px-form-item :label="formValue.isNeedCalculate === 1 ? '选择点位' : '选择指标'" prop="constantValue">
                  <px-select
                    v-if="formValue.isNeedCalculate === 1"
                    v-model="formValue.intouchPackageName"
                    clearable
                    filterable
                    remote
                    :remote-method="tagCodeRemote"
                    placeholder="请输入点位精确查找"
                    style="width: 40%"
                    @change="changePackageName"
                  >
                    <px-option v-for="item in tagCodeList" :key="item.id" :label="item.name" :value="item.value" />
                  </px-select>
                  <px-select
                    v-else
                    v-model="formValue.intouchPackageName"
                    clearable
                    filterable
                    remote
                    :remote-method="tagCodeRemote"
                    placeholder="请输入指标精确查找"
                    style="width: 40%"
                    @change="changePackageName"
                  >
                    <px-option v-for="item in tagCodeList" :key="item.id" :label="item.name" :value="item.value" />
                  </px-select>
                  <px-button @click="add">+</px-button>
                  <px-button @click="subtract">-</px-button>
                  <px-button @click="multiply">*</px-button>
                  <px-button @click="divide">/</px-button>
                  <px-button @click="parentheses">()</px-button>
                </px-form-item>
              </px-col>
            </px-row>
            <px-row>
              <px-col v-if="formValue.isNeedCalculate === 1" :span="24">
                <px-form-item label="所需点位" prop="tagCodes">
                  <px-input v-model="formValue.tagCodes" clearable placeholder="自动带出'|'分隔" maxlength="200" />
                </px-form-item>
              </px-col>
              <px-col v-if="formValue.isNeedCalculate === 2" :span="24">
                <px-form-item label="所需指标" prop="tagCodes">
                  <px-input v-model="formValue.tagCodes" clearable placeholder="自动带出'|'分隔" maxlength="200" />
                </px-form-item>
              </px-col>
              <px-col v-if="formValue.isNeedCalculate !== 0" :span="8">
                <px-form-item label="绑定点位" prop="tagCode">
                  <px-select
                    v-model="formValue.tagCode"
                    :disabled="drawerType === 'edit'"
                    filterable
                    clearable
                    placeholder="请选择"
                    style="width: 100%"
                    @change="handleChangeCode"
                  >
                    <px-option v-for="item in formValue.tagCodes?.split(' | ')" :key="item" :label="item" :value="item" />
                  </px-select>
                </px-form-item>
              </px-col>
              <px-col v-if="formValue.isNeedCalculate === 1" :span="8">
                <px-form-item label="需要积分点位" prop="integralCodes">
                  <px-select v-model="formValue.integralCodes" filterable multiple clearable placeholder="请选择" style="width: 100%">
                    <px-option v-for="item in formValue.tagCodes?.split(' | ')" :key="item" :label="item" :value="item" />
                  </px-select>
                </px-form-item>
              </px-col>
              <px-col v-if="formValue.isNeedCalculate === 1" :span="8">
                <px-form-item label="需要做差点位" prop="minusCodes">
                  <px-select v-model="formValue.minusCodes" filterable multiple clearable placeholder="请选择" style="width: 100%">
                    <px-option v-for="item in formValue.tagCodes?.split(' | ')" :key="item" :label="item" :value="item" />
                  </px-select>
                </px-form-item>
              </px-col>
            </px-row>
          </template>
        </EditDropDown>
      </px-form>
    </px-scrollbar>
    <div class="info-form-btns">
      <px-button @click="backMainPage">取消</px-button>
      <px-button type="primary" @click="handleSubmit(formRef)">保存</px-button>
    </div>
  </div>
</template>
<script setup lang="ts">
import { queryDictData } from "@/api/common";
import { querySystemSelect } from "@/api/equip/archive";
import { createMeasure, getMeasure, getMonitorEntity, getPointCodeAndUnit, updateMeasure } from "@/api/system/measure";
import { queryListByEqpIds } from "@/api/system/pointManage";
import EditDropDown from "@/views/all/equip/components/EditDropDown.vue";
import { PxMessage } from "px-ui";
import { computed, reactive, ref, toRefs, watch } from "vue";

// 调用父级-返回主页、查询列表方法
const emits = defineEmits(["backMainPage", "queryTable"]);
// 父级传过来的值
const props = defineProps(["isMain", "isView", "drawerType", "measureCode"]);
// 显示隐藏
const isMain = computed(() => props.isMain);
const isView = computed(() => props.isView);

const defaultProps = {
  children: "children",
  label: "name",
  value: "value",
  multiple: true
};

const cascaderProps = {
  children: "children",
  label: "name",
  value: "value"
};

const cascaderRef = ref();

// 页面本身的值
const formRef = ref();
const state = reactive<any>({
  formValue: {
    decimalPlaces: 1,
    isNeedCalculate: 0,
    measureName: "",
    measureUnit: "",
    measureTypeCode: "",
    monitorEntityType: "",
    monitorEntityId: "",
    monitorMaterialId: "",
    measureSource: "",
    calculateFormula: ""
  },
  measureUnitList: [], // 指标单位列表
  measureTypeCodeList: [], // 指标类型列表
  derivedTypesList: [], // 衍生指标列表
  statisticsCyclesList: [], // 衍生指标统计周期列表
  facList: [], // 所属厂区列表
  monitorEntityTypeList: [], // 监控实体类型列表
  monitorEntityIdParams: [], // 监控实体列表请求参数
  monitorEntityIdList: [], // 监控实体列表
  monitorMaterialIdList: [], // 监控物料列表
  monitorWasteMaterialIdList: [], // 监控物料列表废弃物
  measureSourceList: [], // 指标来源列表
  tagCodeList: [],
  isGenerateList: [
    {
      label: "是",
      value: 1
    },
    {
      label: "否",
      value: 0
    }
  ],
  customTagCodeList: [], // 选择点位生成的下拉框
  measureTagList: []
});
const {
  formValue,
  measureUnitList,
  measureTypeCodeList,
  derivedTypesList,
  statisticsCyclesList,
  facList,
  monitorEntityTypeList,
  monitorEntityIdParams,
  monitorEntityIdList,
  monitorMaterialIdList,
  monitorWasteMaterialIdList,
  measureSourceList,
  tagCodeList,
  isGenerateList,
  customTagCodeList,
  measureTagList
} = toRefs(state);

const entityTypeProps = {
  children: "children",
  label: "name",
  value: "code",
  checkStrictly: true,
  disabled: item => item.type === "className"
};

// // 表单校验规则
const rules = computed(() => ({
  measureName: [{ required: true, message: "指标名称不能为空", trigger: "change" }],
  measureUnit: [{ required: true, message: "指标单位不能为空", trigger: "change" }],
  facCode: [{ required: true, message: "所属厂区不能为空", trigger: "change" }],
  measureTypeCode: [{ required: true, message: "指标类型不能为空", trigger: "change" }],
  monitorEntityType: [
    {
      required: ["1", "2", "3", "4"].includes(formValue.value.measureTypeCode),
      message: "监控实体类型不能为空",
      trigger: "change"
    }
  ],
  monitorEntityId: [
    {
      required: ["1", "2", "3", "4"].includes(formValue.value.measureTypeCode),
      message: "监控实体不能为空",
      trigger: "change"
    }
  ],
  monitorMaterialId: [
    {
      required: ["1", "2", "3", "4"].includes(formValue.value.measureTypeCode),
      message: "监控物料不能为空",
      trigger: "change"
    }
  ],
  // statisticsCycles: [
  //   {
  //     required: ["1", "2", "3", "4"].includes(formValue.value.measureTypeCode) && formValue.value.derivedTypes?.length !== 0,
  //     message: "衍生指标统计周期不能为空",
  //     trigger: "change"
  //   }
  // ],
  measureSource: [{ required: true, message: "指标来源不能为空", trigger: "change" }],
  isDerived: [{ required: true, message: "生成衍生指标不能为空", trigger: "change" }],
  calculateFormula: [{ required: true, message: "计算公式不能为空", trigger: "change" }],
  tagCode: [{ required: true, message: "绑定点位不能为空", trigger: "change" }]
}));
// 监视isMain和isView值
watch(isMain, async val => {
  if (!val && !props.isView) {
    formRef.value?.resetFields();
    queryAllList();
    if (props.drawerType === "add") {
      formValue.value.decimalPlaces = 1;
      formValue.value.isNeedCalculate = 0;
      monitorEntityIdParams.value = [];
    } else if (props.drawerType === "edit") {
      formValue.value = await getMeasure({ measureCode: props.measureCode });
      monitorEntityIdList.value =
        formValue.value.monitorEntityType === "EQP"
          ? [
              {
                id: 1,
                name: formValue.value.monitorEntityIdDesc,
                value: formValue.value.monitorEntityId
              }
            ]
          : [
              {
                id: 1,
                name: formValue.value.monitorEntityIdDesc,
                code: formValue.value.monitorEntityId
              }
            ];
      formValue.value.tagCodes = formValue.value.tagCodes?.join(" | ");
    }
  } else {
    formRef.value?.resetFields();
  }
});
// 查询所有下拉框
const queryAllList = async () => {
  // 指标单位
  measureUnitList.value = await queryDictData({ typeCode: "MEASURE_UNIT" });
  // 指标类型
  measureTypeCodeList.value = await queryDictData({ typeCode: "MEASURE_TYPE" });
  // 衍生指标
  // derivedTypesList.value = await queryDictData({ typeCode: "DERIVED_MEASURE_TYPE" });
  // 衍生指标统计周期
  // statisticsCyclesList.value = await queryDictData({ typeCode: "statistics_cycle" });
  // 所属厂区
  // facList.value = await queryDictData({ typeCode: "factoryArea" });
  // 监控实体类型
  monitorEntityTypeList.value = await queryDictData({ typeCode: "MONITOR_ENTITY_TYPE" });
  // 监控物料
  monitorMaterialIdList.value = await queryDictData({ typeCode: "MONITOR_MATERIAL" });
  // 监控物料废弃物
  monitorWasteMaterialIdList.value = await queryDictData({ typeCode: "MONITOR_MATERIAL_WASTE" });
  // 指标来源
  measureSourceList.value = await queryDictData({ typeCode: "MEASURE_SOURCE" });
  // intouchPackageNameList.value = await queryDictData({ typeCode: "INTOUCH_PACKAGE_NAME" });
  // 标签
  measureTagList.value = await queryDictData({ typeCode: "measure_tag" });
};
// 选中监控实体类型-整理监控实体参数
const changeMonitorEntityType = () => {
  if (formValue.value.monitorEntityType === "FAC") {
    // 厂区
    monitorEntityIdParams.value = ["FAC"];
  } else if (formValue.value.monitorEntityType === "BUILD") {
    // 建筑
    monitorEntityIdParams.value = ["FAC", "BUILD"];
  } else if (formValue.value.monitorEntityType === "FLOOR") {
    // 楼层
    monitorEntityIdParams.value = ["FAC", "BUILD", "FLOOR"];
  } else if (formValue.value.monitorEntityType === "ROOM") {
    // 房间
    monitorEntityIdParams.value = ["FAC", "BUILD", "FLOOR", "ROOM"];
  }
  formValue.value.monitorEntityId = "";
  monitorEntityIdList.value = [];
};
// 监控实体下拉框-选择不同的值显示的数据不一样
const focusMonitorEntityIdList = async () => {
  // 设备的处理放到监控实体过滤时触发
  if (formValue.value.monitorEntityType === "EQP") {
    return;
  }
  if (formValue.value.monitorEntityType === "SYSTEM") {
    // 系统
    monitorEntityIdList.value = await querySystemSelect({ factoryArea: formValue.value.facCode });
  } else {
    // 厂区、建筑、楼层、房间
    monitorEntityIdList.value = await getMonitorEntity({ facCode: formValue.value.facCode, monitorEntityTypes: monitorEntityIdParams.value });
  }
};
// 监控实体过滤,需要节流
const monitorEntityIdRemote = async val => {
  // 设备必须输入内容才能调用接口，否则10w+数据会页面卡死
  if (val) {
    const data = await queryListByEqpIds({ facCode: formValue.value.facCode, eqpIds: [val.trim()] });
    if (data && data.length > 0) {
      monitorEntityIdList.value = data.map(item => ({ id: item.eqpId, value: item.eqpId, name: item.eqpId }));
    }
  } else {
    monitorEntityIdList.value = [];
  }
};

const handleChangeIsCalc = () => {
  formValue.value.tagCode = "";
  formValue.value.tagUnit = "";
  formValue.value.tagUnitDesc = "";
  formValue.value.className = "";
  formValue.value.systemCode = "";
};
// 计算否情况-绑定点位过滤,需要节流
const tagCodeRemote = async val => {
  // 绑定点位必须输入内容才能调用接口，否则10w+数据会页面卡死
  if (val) {
    const data = await getPointCodeAndUnit({ tagCode: val.trim() });
    if (data && data.length > 0) {
      tagCodeList.value = data.map((item, index) => ({
        id: index + 1,
        value: item.tagCode,
        label: item.tagCode,
        className: item.className,
        systemCode: item.systemCode,
        tagUnit: item.tagUnit,
        tagUnitDesc: item.tagUnitDesc
      }));
    }
  } else {
    tagCodeList.value = [];
    //   formValue.value.tagUnit = "";
    //   formValue.value.className = "";
    //   formValue.value.systemCode = "";
  }
};
// 选中点位下拉框-获取点位科室、系统、单位
const changeTagCode = val => {
  console.log("改变", val, tagCodeList.value);
  formValue.value.tagUnit = tagCodeList.value[0].tagUnit;
  formValue.value.tagUnitDesc = tagCodeList.value[0].tagUnitDesc;
  formValue.value.className = tagCodeList.value[0].className;
  formValue.value.systemCode = tagCodeList.value[0].systemCode;
};
// 返回主页面
const backMainPage = () => {
  emits("backMainPage");
  formRef.value?.resetFields();
  formValue.value = {
    decimalPlaces: 1,
    isNeedCalculate: 0,
    measureName: "",
    measureUnit: "",
    measureTypeCode: "",
    monitorEntityType: "",
    monitorEntityId: "",
    monitorMaterialId: "",
    measureSource: "",
    calculateFormula: ""
  };
};
// 提交
const handleSubmit = async (formEl: any) => {
  if (!formEl) return;
  await formEl.validate(async valid => {
    if (valid) {
      const { monitorMaterialId, tagCodes, measureTags, monitorEntityId } = formValue.value;
      const res = measureTags?.map(item => (Array.isArray(item) ? item[item.length - 1] : item)) || [];
      if (props.drawerType === "add") {
        await createMeasure({
          ...formValue.value,
          monitorMaterialId: monitorMaterialId ? monitorMaterialId[monitorMaterialId?.length - 1] : "",
          monitorEntityId: monitorEntityId ? monitorEntityId[monitorEntityId?.length - 1] : "",
          tagCodes: tagCodes ? tagCodes?.split(" | ") : [],
          measureTags: res
        });
        PxMessage.success("创建成功");
        customTagCodeList.value = [];
        backMainPage();
        emits("queryTable");
      } else if (props.drawerType === "edit") {
        const id = Array.isArray(monitorMaterialId) ? monitorMaterialId[monitorMaterialId?.length - 1] : monitorMaterialId ? monitorMaterialId : "";
        const entityId = Array.isArray(monitorEntityId) ? monitorEntityId[monitorEntityId?.length - 1] : monitorEntityId ? monitorEntityId : "";
        await updateMeasure({
          ...formValue.value,
          monitorMaterialId: id,
          monitorEntityId: entityId,
          tagCodes: tagCodes ? tagCodes?.split(" | ") : [],
          measureTags: res
        });
        PxMessage.success("编辑成功");
        customTagCodeList.value = [];
        backMainPage();
        emits("queryTable");
      }
    }
  });
};

// //计算
function performOperation(operation) {
  // 获取光标位置
  const eleId = document.getElementById("myInput");
  const cursorPosition = eleId.selectionStart;
  // 分割字符串，获取光标前面的内容和光标后面的内容
  const beforeCursor = formValue.value.calculateFormula.slice(0, cursorPosition);
  const afterCursor = formValue.value.calculateFormula.slice(cursorPosition);
  console.log(beforeCursor, afterCursor);

  formValue.value.calculateFormula = `${beforeCursor}${operation}${afterCursor}`;
}
const add = () => performOperation("+");
const subtract = () => performOperation("-");
const multiply = () => performOperation("*");
const divide = () => performOperation("/");
const parentheses = () => performOperation("()");

const handleChangeCode = async val => {
  const res = await getPointCodeAndUnit({ tagCode: val.trim() });
  // const res = customTagCodeList.value?.find(item => item.value === val);
  formValue.value.tagUnit = res[0]?.tagUnit;
  formValue.value.tagUnitDesc = res[0]?.tagUnitDesc;
  formValue.value.className = res[0]?.className;
  formValue.value.systemCode = res[0]?.systemCode;
};

//选择点位下拉框
const changePackageName = val => {
  console.log("计算", tagCodeList.value, val);
  if (val) {
    // 检查输入框是否已有内容，若有则添加分隔符“|”
    if (formValue.value.tagCodes) {
      if (!formValue.value.tagCodes.includes(val)) {
        formValue.value.tagCodes += " | " + val;
        // customTagCodeList.value = [...customTagCodeList.value, ...tagCodeList.value];
      }
    } else {
      formValue.value.tagCodes = val;
      // // 联动创建点位下拉框
      // customTagCodeList.value = [...customTagCodeList.value, ...tagCodeList.value];
    }
    formValue.value.calculateFormula += val;
    // 重置selectedOption，以便下次选择时能够正确触发change事件
    // 若不希望每次选择后都重置，可移除或注释掉下一行代码
    val = null;
    formValue.value.intouchPackageName = "";
  }
  // 选择点位
  // const arr = formValue.value.tagCodes.split("|");
  // console.log(arr);
};
</script>
<style lang="scss" scoped>
@import url("@/views/all/equip/scss/add-detail.scss");
</style>
